const config = require('../config/index')
const { showToast } = require('./toast.js')
const sm4 = require("miniprogram-sm-crypto").sm4;
const key = 'cd142f7ff13d4ef19a9937ca2fa2a8a4' // 可以为 16 进制串或字节数组，要求为 128 比特

function login(cb) {
  wx.login({
    success: (res) => {
      wxRequest({
        url: `${config.baseUrl}/user/login?code=${res.code}`,
        method: 'POST',
        success(res){
          const newToken = res.data.data
          wx.setStorageSync('InvoiceLoanToken', newToken)
          cb()
        }
      })
    },
  })
}

/**
   * 封装wx.request请求
   * url: 请求地址
   * data： 要传递的参数
   * callback： 请求成功回调函数
   * errFun： 请求失败回调函数
   **/
function wxRequest(options) {
  const { url, data, header = {}, invalidCb = ()=>{}, success, fail, complete, showLoading = true, ...remain } = options
  let newData = {...data}
  if (data) {
    let encryptData = sm4.encrypt(JSON.stringify(newData), key)
    newData = encryptData
  }
  if(showLoading) {
    wx.showLoading({
      title:'加载中...',
      mask: true
    })
  }
  wx.request({
    url: url,
    method: 'GET',
    data: newData,
    dataType: 'json',
    header: {
      'content-type': 'application/json', // 默认值
      Authorization: wx.getStorageSync('InvoiceLoanToken'),
      ...header
    },
    success: function (res) {
      wx.hideLoading()
      if (res.data) {
        let decryptData = sm4.decrypt(res.data, key)
        switch (res.data.code) {
          case 200:
            console.log('decryptData',res.data);
            success?.({
              ...res,
              data: decryptData
            });
            return;
          case 401:
            login(invalidCb)
            return
          default:
            showToast({
              title: res.data.message,
              duration: 3000
            })
            return;
        }       
      } else {
        success?.(res);
      }
    },
    fail: function (res) {
      wx.hideLoading()
      fail?.(res);
    },
    complete: function () {
      complete?.()
    },
    ...remain,
  })
}

const themeMap = {
    spring: {
      primaryColor: '#7CAE26',
      bgClass: 'invoiceLoan_spring_bg',
      borderClass: 'invoiceLoan_spring_border',
      colorClass: 'invoiceLoan_spring_color'
    },
    summer: {
      primaryColor: '#289F6C',
      bgClass: 'invoiceLoan_summer_bg',
      borderClass: 'invoiceLoan_summer_border',
      colorClass: 'invoiceLoan_summer_color'
    },
    autumn: {
      primaryColor: '#FF8227',
      bgClass: 'invoiceLoan_autumn_bg',
      borderClass: 'invoiceLoan_autumn_border',
      colorClass: 'invoiceLoan_autumn_color'
    },
    winter: {
      primaryColor: '#0D86E1',
      bgClass: 'invoiceLoan_winter_bg',
      borderClass: 'invoiceLoan_winter_border',
      colorClass: 'invoiceLoan_winter_color'
    },
}

function getThemeConfig() {
  const theme = wx.getStorageSync('InvoiceLoanTheme')
  return themeMap[theme]
}

module.exports = {
  login,
  wxRequest,
  getThemeConfig
}
